package com.yaorange.service.async;


import com.yaorange.entity.Emp;
import com.yaorange.utils.MailUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;

@Service
public class AsyncServiceImpl implements AsyncService {
    private static final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);

    @Autowired
    private MailUtils mailUtils;


    @Async("asyncServiceExecutor")
    @Override
    public void asyncSendMail(Emp emp) {
        logger.info("邮件发送开始......");
        //实现最多三次发送机会
        boolean isSendOk = false;
        int count = 0;
        while (!isSendOk && count < 3){
            try {
                mailUtils.sendMail(emp.getEmpEmail(),
                        "欢迎入职雅橙科技","合伙人"+emp.getEmpName()+
                                ",雅橙科技欢迎你，公司内部CRM系统账户:"+emp.getEmpAccount()+
                                ",初始密码："+emp.getEmpPassword());
                //标识发送成功
                isSendOk = true;
                logger.info("邮件发送成功..........");
            }catch (Exception e){
                logger.info("第"+(count + 1)+"次邮件发送失败，暂停一秒后再尝试......");
                //休眠1秒再次尝试
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e1) {
                    e1.printStackTrace();
                }
            }
            count ++;//更新发送次数
        }

    }

    //不带返回值
    @Override
    @Async("asyncServiceExecutor")
    public void executeAsync() {
        logger.info("start executeAsync");

        System.out.println("异步线程要做的事情:");
        System.out.println("可以在这里执行批量插入等耗时的事情");
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        logger.info("end executeAsync");
    }

    //带返回值的任务
    @Async("asyncServiceExecutor")
    @Override
    public Future<String> executeAsync1(){
        logger.info("executeAsync1 started.");
        long start = System.currentTimeMillis();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();

        logger.info("executeAsync1 finished, time elapsed: {} ms.", end-start);

        return new AsyncResult<>("executeAsync1 accomplished!");
    }



    //带返回值的任务
    @Async("asyncServiceExecutor")
    @Override
    public Future<String> executeAsync2(CountDownLatch latch) {
        logger.info("executeAsync2 started.");
        long start = System.currentTimeMillis();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();

        logger.info("executeAsync2 finished, time elapsed: {} ms.", end-start);
        //调用latch.countDown();使得计数器-1
        latch.countDown();
        return new AsyncResult<>("executeAsync2 accomplished!");
    }
}
